<template>
  <div id="Roles">
      <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<el-card class="box-card">
    <el-button type="primary" @click="insertRoles">添加角色</el-button>
    <!-- 表格 -->
    <el-table
    border
    :data="roleList"
    style="width: 100%">
    <el-table-column type="expand">
     <template slot-scope="scope">
       <el-row v-for="item1 in scope.row.children" :key="item1.id" style="border-top: 1px solid #eee;">
         <el-col :span='5'>
           <el-tag closable @close="removeTag(scope.row,item1.id)">
             {{item1.authName}}
           </el-tag>
           <i class="el-icon-caret-right"></i>
         </el-col>
         <el-col :span='19'>
           <el-row v-for="item2 in item1.children" :key='item2.id' class="item2">
             <el-col :span='6'>
               <el-tag type='success' closable @close="removeTag(scope.row,item2.id)">
             {{item2.authName}}
           </el-tag>
           <i class="el-icon-caret-right"></i>
             </el-col>
             <el-col :span='18' style="width:45%">
                 <el-tag type='warning' v-for="item3 in item2.children" :key='item3.id' class="item3" closable @close="removeTag(scope.row,item3.id)">
             {{item3.authName}}
           </el-tag>
             </el-col>
           </el-row>
         </el-col>
       </el-row>
        <!-- pre标签可以美化一下返回的对象 -->
       <!-- <pre>
         {{scope.row}}
       </pre> -->
     </template>
    </el-table-column>
    <el-table-column
      type="index"
      label="#"
      width="100">
    </el-table-column>
    <el-table-column
      label="角色名称"
      prop="roleName">
    </el-table-column>
    <el-table-column
      label="角色描述"
      prop="roleDesc">
    </el-table-column>
    <el-table-column
      label="操作">
      <template slot-scope="scope">
        <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
        <el-button type="primary"  size="mini" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
           </el-tooltip>
            <el-tooltip class="item" effect="dark" content="权限" placement="top" :enterable="false">
          <el-button
          size="mini"
          type="warning"
          icon="el-icon-share"
          @click="showRoles(scope.row)">分配权限</el-button>
           </el-tooltip>
      </template>
    </el-table-column>
    
  </el-table>
   <!-- 弹出添加用户对话框 -->
<el-dialog title="添加角色" :visible.sync="dialogFormVisible">
  <el-form :model="rolesForm" class="demo-ruleForm" :rules="rules" ref="rolesForm" label-width="100px">
    <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="rolesForm.roleName"></el-input>
  </el-form-item>
    <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="rolesForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offForm">取 消</el-button>
    <el-button type="primary" @click="sureForm">确 定</el-button>
  </div>
</el-dialog>
 <!-- 弹出修改用户对话框 -->
<el-dialog title="修改角色" :visible.sync="editFormVisible">
  <el-form :model="editRolesForm" class="demo-ruleForm" :rules="rules" ref="editRolesForm" label-width="100px">
    <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="editRolesForm.roleName"></el-input>
  </el-form-item>
    <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editRolesForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editOffForm">取 消</el-button>
    <el-button type="primary" @click="editSureForm">确 定</el-button>
  </div>
</el-dialog>
 <!-- 弹出分配权限用户对话框 -->
<el-dialog title="分配权限" :visible.sync="showRolesFrom" @close='offRoles'>
  <!-- node-key是指定每个选项的指定id -->
 <el-tree :data="rolesTreeList" :props="defaultProps" show-checkbox node-key='id' :default-expand-all='true' :default-checked-keys='defKeys' ref="treeRef"></el-tree>
  <div slot="footer" class="dialog-footer">
    <el-button @click="rolesOffForm">取 消</el-button>
    <el-button type="primary" @click="rolesSureForm">确 定</el-button>
  </div>
</el-dialog>
</el-card>
  </div>
</template>

<script>
export default {
  data(){
    return{
      roleList:[],
      dialogFormVisible:false,
      editFormVisible:false,
      showRolesFrom:false,
      rolesForm:{
        roleName:'',
        roleDesc:''
      },
      editRolesForm:{},
      rules:{
          roleName:[
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
          ],
          roleDesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
          ],
        },
        rolesTreeList:[],
        // authName是接口对应的字段
        defaultProps:{
          label:'authName',
          children: 'children',
        },
        // defKeys写入对应权限对应的id会默认勾选的
        defKeys:[],
        //当前分配的权限角色id
        roleId:'',
    }
  },
  created(){
    this.getRoleList();
  },
  methods:{
    async getRoleList(){
      const {data:res}=await this.$http.get('roles')
      if(res.meta.status!==200){
        return this.$message.error('获取角色列表失败')
      }
      this.roleList=res.data
    },
    //添加角色
    async insertRoles(){
      this.dialogFormVisible=true
      
    },
    offForm(){
      this.dialogFormVisible=false
      this.$refs.rolesForm.resetFields()
    },
    editOffForm(){
      this.editFormVisible=false
      this.$refs.editRolesForm.resetFields()
    },
    sureForm(){
      // 点击确定按钮验证输入框是否输入
        this.$refs.rolesForm.validate(async valid=>{
          if(!valid) return
          // 发送添加请求
          const {data:res}=await this.$http.post('roles',this.rolesForm)
          if(res.meta.status!==201){
            this.$message.error('添加失败')
          }else{
             this.$message.success('添加成功')
             this.dialogFormVisible = false;
            //  重新获取用户列表
             this.getRoleList()
          }
        })
    },
    //查询用户id获取信息
    async handleEdit(index,row){
      this.editFormVisible = true;
      const {data:res}=await this.$http.get(`roles/${row.id}`)
      if(res.meta.status!==200) return this.$message.error('查询用户失败')
      this.editRolesForm=res.data
    },
    //编辑接口
    async editSureForm(){
        // 点击确定按钮验证输入框是否输入
        this.$refs.editRolesForm.validate(async valid=>{
          if(!valid) return
          // 发送添加请求
            const {data:res}=await this.$http.put(`roles/${this.editRolesForm.roleId}`,{roleName:this.editRolesForm.roleName,roleDesc:this.editRolesForm.roleDesc})
          if(res.meta.status!==200){
            this.$message.error('修改失败')
          }else{
             this.$message.success('修改成功')
             this.editFormVisible = false;
            //  重新获取用户列表
            this.getRoleList()
          }
        })
    },
    handleDelete(index,row){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      }).then(async () => {
      const { data:res }=await this.$http.delete(`roles/${row.id}`)
      if(res.meta.status === 200){
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
      this.getRoleList()
      }
      
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
    },
    // 根据id删除三级菜单对应的权限
    async removeTag(role,rightId){
      const confimResult=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      }).catch(err=>err);
      if(confimResult!=='confirm'){
        return this.$message.info('取消删除')
      }
      console.log('确认删除');
      const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if(res.meta.status!==200){
        return this.$message.error('删除权限失败')
      }
        this.$message.success('删除权限成功')
        // this.getRoleList() 不建议直接覆盖数据  因为展开列表会合上
        role.children=res.data  //从返回删除权限的接口返回值data覆盖数据
    },
    // 分配权限
    async showRoles(role){
      this.roleId=role.id
      this.showRolesFrom=true
      const {data:res}=await this.$http.get('rights/tree')
      if(res.meta.status!==200){
        return this.$message.error('获取权限失败')
      }
      this.rolesTreeList=res.data
      //递归获取三级节点的id
      this.getLeafkeys(role,this.defKeys)
    },
    rolesOffForm(){
      this.showRolesFrom=false
    },
    async rolesSureForm(){
        console.log(this.roleId);
      this.showRolesFrom=false
     const keys=[
      //  获取已经选中的id数组  getCheckedKeys是element的方法
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
     ]
     const idStr=keys.join(',')
      //通过接口选择权限渲染到对应角色
      const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if(res.meta.status!==200){
        return this.$message.error('更新权限失败')
      }
      this.$message.success('更新权限成功')
      this.getRoleList()

    },
    //通过递归的方式，获取角色下所有三级权限的id，并保存到defKeys中 node表示是否为三级权限节点,arr是个数组
    getLeafkeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafkeys(item,arr)
      })
    },
    //监听分配权限对话框
    offRoles(){
      this.defKeys=[]
    }
  }
}
</script>

<style lang="less" scoped>
#Roles{
  .box-card{
    margin: 15px 0;
    .el-table{
      margin: 10px 0;
      .el-row{
        display: flex;
        align-items: center;
        //  border-bottom: 1px solid #ff0000;
        //  &:nth-child(1){
        //    border-top: 1px solid #ff0000;
        //  }
         &:nth-child(5){
          border-bottom: 1px solid #eee;
        }
        .el-tag{
        margin: 7px;
      }
      .item2{
        border-top: 1px solid #eee;
        &:nth-child(1){
          border-top: 0;
        }

      }
      }
    }
  }
}
</style>